package com.lagou.sqlSession;

import com.lagou.config.BoundSql;
import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author user
 */
public class SimpleExecutor implements Executor {

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object object) throws Exception {
        return this.executeUpdate(configuration, mappedStatement, object);
    }

    @Override
    public int delete(Configuration configuration, MappedStatement mappedStatement, Object object) throws Exception {
        return this.executeUpdate(configuration, mappedStatement, object);
    }

    @Override
    public void insert(Configuration configuration, MappedStatement mappedStatement, Object object) throws Exception {
        this.executeUpdate(configuration, mappedStatement, object);
    }

    private int executeUpdate(Configuration configuration, MappedStatement mappedStatement, Object object) throws Exception {
        BoundSql boundSql = mappedStatement.createBoundSql();
        // 1. 获取预处理对象：preparedStatement
        PreparedStatement preparedStatement = this.createPreparedStatement(configuration, boundSql);
        //
        this.fillParamter(preparedStatement, mappedStatement, boundSql, new Object[]{object});
        return preparedStatement.executeUpdate();
    }

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 1. 获取sql语句 : select * from user where id = #{id} and username = #{username}
        //转换sql语句： select * from user where id = ? and username = ? ，转换的过程中，还需要对#{}里面的值进行解析存储
        BoundSql boundSql = mappedStatement.createBoundSql();
        // 2. 获取预处理对象：preparedStatement
        PreparedStatement preparedStatement = this.createPreparedStatement(configuration, boundSql);
        // 3. 设置参数
        //获取到了参数的全路径
        this.fillParamter(preparedStatement, mappedStatement, boundSql, params);
        // 4. 执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        ArrayList<Object> objects = new ArrayList<>();
        // 5. 封装返回结果集
        //元数据
        ResultSetMetaData metaData = resultSet.getMetaData();
        while (resultSet.next()) {
            Object o = this.fillObject(resultTypeClass, metaData, resultSet);
            objects.add(o);
        }
        return (List<E>) objects;
    }

    private void fillParamter(PreparedStatement preparedStatement, MappedStatement mappedStatement, BoundSql boundSql, Object[] params) throws ClassNotFoundException, NoSuchFieldException, SQLException, IllegalAccessException {
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramtertypeClass = getClassType(paramterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            Object o = this.convertParamsValue(paramtertypeClass, content, params[0]);
            preparedStatement.setObject(i + 1, o);
        }
    }

    private Object convertParamsValue(Class<?> paramtertypeClass, String content, Object param) throws NoSuchFieldException, IllegalAccessException {
        if (paramtertypeClass.isPrimitive()) {
            return param;
        }
        if (String.class.isAssignableFrom(paramtertypeClass) || Number.class.isAssignableFrom(paramtertypeClass)) {
            return param;
        }
        //反射
        Field declaredField = paramtertypeClass.getDeclaredField(content);
        //暴力访问
        declaredField.setAccessible(true);
        return declaredField.get(param);
    }


    private PreparedStatement createPreparedStatement(Configuration configuration, BoundSql boundSql) throws SQLException {
        // 1. 注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();
        return connection.prepareStatement(boundSql.getSqlText());
    }

    private Object fillObject(Class<?> resultTypeClass, ResultSetMetaData metaData, ResultSet resultSet) throws SQLException, InstantiationException, IllegalAccessException {
        Object o = resultTypeClass.newInstance();
        for (int i = 1; i <= metaData.getColumnCount(); i++) {
            // 字段名
            String columnName = metaData.getColumnName(i);
            // 字段的值
            Object value = resultSet.getObject(columnName);
            //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
            try {
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            } catch (Exception e) {
                // 忽略没有找到到字段
                System.err.println(e.getMessage());
            }
        }
        return o;
    }

    private Class<?> getClassType(String paramterType) throws ClassNotFoundException {
        if (paramterType != null) {
            return Class.forName(paramterType);
        }
        return null;
    }


}
